import React, { useState, useEffect, useRef } from "react";
import dayjs from "dayjs";
import { Button, message, Modal, Table, Space, Input, Form, InputNumber, DatePicker } from "antd";
import { PlusOutlined, DeleteOutlined, EditOutlined, UploadOutlined } from "@ant-design/icons";
import { getLocationList, createLocation, updateLocation, deleteLocation, LocationItem } from "../../api/gis";
import LocationBatchUploadModal from "./LocationBatchUploadModal";

interface LocationManagementProps {
  planetId: number;
}

const LocationManagement: React.FC<LocationManagementProps> = ({ planetId }) => {
  // 地名管理相关状态
  const [locations, setLocations] = useState<LocationItem[]>([]);
  const [locationLoading, setLocationLoading] = useState(false);
  const [locationModalVisible, setLocationModalVisible] = useState(false);
  const [editingLocation, setEditingLocation] = useState<LocationItem | null>(null);
  const [selectedLocationKeys, setSelectedLocationKeys] = useState<React.Key[]>([]);
  const [batchDeleteLoading, setBatchDeleteLoading] = useState(false);
  const [locationForm] = Form.useForm();
  const [locationFilterForm] = Form.useForm();

  // 批量上传相关状态
  const [batchUploadModalVisible, setBatchUploadModalVisible] = useState(false);

  // 分页状态
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [total, setTotal] = useState(0);

  // 表格容器ref和滚动高度
  const tableContainerRef = useRef<HTMLDivElement>(null);
  const [tableScrollY, setTableScrollY] = useState(0);

  // 获取地点列表
  const fetchLocations = async (page = 1, size = 20, filters = {}) => {
    setLocationLoading(true);
    try {
      const formValues = locationFilterForm.getFieldsValue();

      // 处理日期范围
      let approvalDateGte = "";
      let approvalDateLte = "";
      if (formValues.approval_date_range && formValues.approval_date_range.length === 2) {
        approvalDateGte = formValues.approval_date_range[0].format("YYYY-MM-DD");
        approvalDateLte = formValues.approval_date_range[1].format("YYYY-MM-DD");
      }

      const response = await getLocationList({
        planet_id: planetId,
        page,
        page_size: size,
        location_name: formValues.location_name || "",
        location_name_zh: formValues.location_name_zh || "",
        location_type: formValues.location_type || "",
        location_level: formValues.location_level,
        approval_date_gte: approvalDateGte,
        approval_date_lte: approvalDateLte,
        ...filters,
      });

      if (response.code === 200) {
        setLocations(response.data.list);
        setTotal(response.data.count);
        setCurrent(response.data.page);
        setPageSize(response.data.page_size);
      } else {
        message.error(response.msg || "获取地点列表失败");
      }
    } catch (error) {
      console.error("获取地点列表失败:", error);
      message.error((error as any)?.message || "获取地点列表失败");
    } finally {
      setLocationLoading(false);
    }
  };

  // 组件加载时获取数据
  useEffect(() => {
    fetchLocations();
  }, [planetId]);

  // 筛选表单提交
  const onLocationFilterFinish = () => {
    setCurrent(1);
    fetchLocations(1, pageSize);
  };

  // 分页处理
  const handleLocationTableChange = (paginationInfo: any) => {
    setCurrent(paginationInfo.current);
    setPageSize(paginationInfo.pageSize);
    fetchLocations(paginationInfo.current, paginationInfo.pageSize);
  };

  // 新建地点
  const handleCreateLocation = () => {
    setEditingLocation(null);
    locationForm.resetFields();
    setLocationModalVisible(true);
  };

  // 编辑地点
  const handleEditLocation = (record: LocationItem) => {
    setEditingLocation(record);
    locationForm.setFieldsValue({
      location_name: record.location_name,
      location_name_zh: record.location_name_zh,
      approval_date: record.approval_date ? dayjs(record.approval_date) : null,
      location_race: record.location_race,
      location_type: record.location_type,
      location_diameter: record.location_diameter,
      location_level: record.location_level,
      location_name_origin: record.location_name_origin,
      center_latitude: record.center_latitude,
      center_longitude: record.center_longitude,
    });
    setLocationModalVisible(true);
  };

  // 删除地点
  const handleDeleteLocation = async (record: LocationItem) => {
    Modal.confirm({
      title: "确认删除",
      content: `确定要删除地点 "${record.location_name_zh}" 吗？`,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        try {
          const response = await deleteLocation({ id_list: [record.id] });
          if (response.code === 200) {
            message.success("删除成功");
            fetchLocations(current, pageSize);
          } else {
            message.error(response.msg || "删除失败");
          }
        } catch (error) {
          console.error("删除地点失败:", error);
          message.error((error as any)?.message || "删除失败");
        }
      },
    });
  };

  // 批量删除地点
  const handleBatchDeleteLocation = () => {
    if (selectedLocationKeys.length === 0) {
      message.warning("请选择要删除的地点");
      return;
    }
    Modal.confirm({
      title: "确认批量删除",
      content: `确定要删除选中的 ${selectedLocationKeys.length} 个地点吗？`,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        setBatchDeleteLoading(true);
        try {
          const response = await deleteLocation({ id_list: selectedLocationKeys.map((id) => Number(id)) });
          if (response.code === 200) {
            message.success("批量删除成功");
            setSelectedLocationKeys([]);
            fetchLocations(current, pageSize);
          } else {
            message.error(response.msg || "批量删除失败");
          }
        } catch (error) {
          console.error("批量删除失败:", error);
          message.error((error as any)?.message || "批量删除失败");
        } finally {
          setBatchDeleteLoading(false);
        }
      },
    });
  };

  // 保存地点（新建或编辑）
  const handleSaveLocation = async () => {
    try {
      const values = await locationForm.validateFields();

      // 处理日期格式
      const processedValues = {
        ...values,
        approval_date: values.approval_date ? values.approval_date.format("YYYY-MM-DD") : "",
      };

      if (editingLocation) {
        // 编辑
        const response = await updateLocation({
          id: editingLocation.id,
          planet_id: planetId,
          ...processedValues,
        });
        if (response.code === 200) {
          message.success("修改成功");
          setLocationModalVisible(false);
          fetchLocations(current, pageSize);
        } else {
          message.error(response.msg || "修改失败");
        }
      } else {
        // 新建
        const response = await createLocation({
          planet_id: planetId,
          ...processedValues,
        });
        if (response.code === 200) {
          message.success("创建成功");
          setLocationModalVisible(false);
          fetchLocations(current, pageSize);
        } else {
          message.error(response.msg || "创建失败");
        }
      }
    } catch (error) {
      console.error("保存地点失败:", error);
      message.error((error as any)?.message || "保存失败");
    }
  };

  // 批量上传成功回调
  const handleBatchUploadSuccess = () => {
    fetchLocations(current, pageSize);
  };

  // 表格选择配置
  const locationRowSelection = {
    selectedRowKeys: selectedLocationKeys,
    columnWidth: 50,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedLocationKeys(newSelectedRowKeys);
    },
  };

  // 地点表格列定义
  const locationColumns = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
      width: 80,
      ellipsis: true,
    },
    {
      title: "地点名称",
      dataIndex: "location_name",
      key: "location_name",
      width: 150,
      ellipsis: true,
      render: (text: any) => (text === undefined || text === null || text === "" ? "-" : text),
    },
    {
      title: "中文名称",
      dataIndex: "location_name_zh",
      key: "location_name_zh",
      width: 150,
      ellipsis: true,
      render: (text: any) => (text === undefined || text === null || text === "" ? "-" : text),
    },
    {
      title: "批准时间",
      dataIndex: "approval_date",
      key: "approval_date",
      width: 120,
      ellipsis: true,
      render: (text: any) => (text === undefined || text === null || text === "" ? "-" : text),
    },
    {
      title: "地点种族",
      dataIndex: "location_race",
      key: "location_race",
      width: 120,
      ellipsis: true,
      render: (text: any) => (text === undefined || text === null || text === "" ? "-" : text),
    },
    {
      title: "地点类型",
      dataIndex: "location_type",
      key: "location_type",
      width: 120,
      ellipsis: true,
      render: (text: any) => (text === undefined || text === null || text === "" ? "-" : text),
    },
    {
      title: "直径",
      dataIndex: "location_diameter",
      key: "location_diameter",
      width: 100,
      ellipsis: true,
      render: (text: any) => (text === undefined || text === null || text === "" ? "-" : text),
    },
    {
      title: "级别",
      dataIndex: "location_level",
      key: "location_level",
      width: 100,
      ellipsis: true,
      render: (text: any) => (text === undefined || text === null || text === "" ? "-" : text),
    },
    {
      title: "原始名称",
      dataIndex: "location_name_origin",
      key: "location_name_origin",
      width: 150,
      ellipsis: true,
      render: (text: any) => (text === undefined || text === null || text === "" ? "-" : text),
    },
    {
      title: "中心纬度",
      dataIndex: "center_latitude",
      key: "center_latitude",
      width: 120,
      ellipsis: true,
      render: (text: any) => (text === undefined || text === null || text === "" ? "-" : text),
    },
    {
      title: "中心经度",
      dataIndex: "center_longitude",
      key: "center_longitude",
      width: 120,
      ellipsis: true,
      render: (text: any) => (text === undefined || text === null || text === "" ? "-" : text),
    },
    {
      title: "创建时间",
      dataIndex: "create_time",
      key: "create_time",
      width: 180,
      ellipsis: true,
      render: (text: any) => (text === undefined || text === null || text === "" ? "-" : text),
    },
    {
      title: "操作",
      key: "action",
      width: 200,
      fixed: "right" as const,
      align: "center" as const,
      render: (_: any, record: LocationItem) => (
        <Space size="small">
          <Button type="link" size="small" icon={<EditOutlined />} onClick={() => handleEditLocation(record)}>
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteLocation(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 计算表格滚动高度
  const calculateTableScrollHeight = () => {
    if (tableContainerRef.current) {
      // 获取整个页面的可用高度
      const pageHeight = window.innerHeight;
      // 减去面包屑、tabs头部、筛选表单、操作按钮等的高度
      const breadcrumbHeight = 48; // 面包屑高度
      const tabsHeaderHeight = 46; // tabs头部高度
      
      // 动态获取筛选表单高度
      const filterFormElement = document.querySelector('.filter-form');
      const filterFormHeight = filterFormElement ? filterFormElement.getBoundingClientRect().height : 64;
      
      const actionButtonsHeight = 56; // 操作按钮区域高度
      const padding = 242; // 各种padding和margin

      const availableHeight =
        pageHeight - breadcrumbHeight - tabsHeaderHeight - filterFormHeight - actionButtonsHeight - padding;
      const tableHeaderHeight = 39; // 表格头部高度
      const scrollHeight = Math.max(availableHeight - tableHeaderHeight, 100); // 最小高度100px

      setTableScrollY(scrollHeight);

      // 直接设置表格容器的高度
      const tableBody = tableContainerRef.current.querySelector(".ant-table-body") as HTMLElement;
      if (tableBody) {
        tableBody.style.height = scrollHeight + "px";
        tableBody.style.maxHeight = scrollHeight + "px";
      }
    }
  };

  useEffect(() => {
    // 延迟计算，确保DOM完全渲染
    const timer = setTimeout(() => {
      calculateTableScrollHeight();
    }, 100);

    window.addEventListener("resize", calculateTableScrollHeight);
    return () => {
      clearTimeout(timer);
      window.removeEventListener("resize", calculateTableScrollHeight);
    };
  }, []); // 当组件挂载时计算

  return (
    <div>
      {/* 筛选表单 */}
      <Form
        form={locationFilterForm}
        className="filter-form"
        onFinish={onLocationFilterFinish}
        labelCol={{ style: { width: 70 } }}
        style={{ marginBottom: 16 }}
      >
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              flexWrap: "wrap",
              gap: "8px 16px",
            }}
          >
            <Form.Item name="location_name" label="英文名称" style={{ width: 260 }}>
              <Input placeholder="请输入英文名称" style={{ width: "100%" }} />
            </Form.Item>
            <Form.Item name="location_name_zh" label="中文名称" style={{ width: 260 }}>
              <Input placeholder="请输入中文名称" style={{ width: "100%" }} />
            </Form.Item>
            <Form.Item name="location_type" label="地名类型" style={{ width: 260 }}>
              <Input placeholder="请输入地名类型" style={{ width: "100%" }} />
            </Form.Item>
            <Form.Item name="location_level" label="地名级别" style={{ width: 260 }}>
              <InputNumber placeholder="请输入地名级别" style={{ width: "100%" }} />
            </Form.Item>
            <Form.Item name="approval_date_range" label="批准时间" style={{ width: 340 }}>
              <DatePicker.RangePicker placeholder={["批准开始时间", "批准结束时间"]} style={{ width: "100%" }} />
            </Form.Item>
          </div>
          <Form.Item style={{ marginLeft: 16 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                筛选
              </Button>
              <Button
                htmlType="button"
                onClick={() => {
                  locationFilterForm.resetFields();
                  fetchLocations(1, pageSize);
                }}
              >
                清除
              </Button>
            </Space>
          </Form.Item>
        </div>
      </Form>

      {/* 操作按钮 */}
      <div style={{ marginBottom: 16, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div>
          <Button
            type="primary"
            danger
            onClick={handleBatchDeleteLocation}
            loading={batchDeleteLoading}
            disabled={selectedLocationKeys.length === 0}
          >
            批量删除
          </Button>
        </div>

        <Space>
          <Button type="primary" icon={<UploadOutlined />} onClick={() => setBatchUploadModalVisible(true)}>
            批量导入
          </Button>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleCreateLocation}>
            新建地点
          </Button>
        </Space>
      </div>

      {/* 数据表格 */}
      <div className="pds-table-container" ref={tableContainerRef}>
        <Table
          rowSelection={locationRowSelection}
          columns={locationColumns}
          dataSource={locations}
          rowKey="id"
          loading={locationLoading}
          pagination={{
            current,
            pageSize,
            total,
            showSizeChanger: true,
            pageSizeOptions: ["10", "20", "50"],
            onChange: (page, size) => {
              setCurrent(page);
              setPageSize(size);
            },
            showTotal: (total) => `共 ${total} 条`,
          }}
          scroll={{ y: tableScrollY, x: "max-content" }}
          bordered
          size="small"
          onChange={handleLocationTableChange}
        />
      </div>

      {/* 新建/编辑地点弹窗 */}
      <Modal
        title={editingLocation ? "编辑地点" : "新建地点"}
        open={locationModalVisible}
        onOk={handleSaveLocation}
        onCancel={() => setLocationModalVisible(false)}
        width={800}
        okText="保存"
        cancelText="取消"
      >
        <Form form={locationForm} layout="vertical" style={{ marginTop: 16 }}>
          <div style={{ display: "flex", gap: 16 }}>
            <div style={{ flex: 1 }}>
              <Form.Item name="location_name" label="地点名称" rules={[{ required: true, message: "请输入地点名称" }]}>
                <Input placeholder="请输入地点名称" />
              </Form.Item>
              <Form.Item
                name="location_name_zh"
                label="中文名称"
                rules={[{ required: true, message: "请输入中文名称" }]}
              >
                <Input placeholder="请输入中文名称" />
              </Form.Item>
              <Form.Item name="approval_date" label="批准时间" rules={[{ required: true, message: "请选择批准时间" }]}>
                <DatePicker placeholder="请选择批准时间" style={{ width: "100%" }} />
              </Form.Item>
              <Form.Item name="location_race" label="地点种族" rules={[{ required: true, message: "请输入地点种族" }]}>
                <Input placeholder="请输入地点种族" />
              </Form.Item>
              <Form.Item name="location_type" label="地点类型" rules={[{ required: true, message: "请输入地点类型" }]}>
                <Input placeholder="请输入地点类型" />
              </Form.Item>
            </div>
            <div style={{ flex: 1 }}>
              <Form.Item name="location_diameter" label="直径" rules={[{ required: true, message: "请输入直径" }]}>
                <InputNumber placeholder="请输入直径" style={{ width: "100%" }} />
              </Form.Item>
              <Form.Item name="location_level" label="级别" rules={[{ required: true, message: "请输入级别" }]}>
                <InputNumber placeholder="请输入级别" style={{ width: "100%" }} />
              </Form.Item>
              <Form.Item name="location_name_origin" label="原始名称">
                <Input placeholder="请输入原始名称" />
              </Form.Item>
              <Form.Item name="center_latitude" label="中心纬度">
                <InputNumber placeholder="请输入中心纬度" style={{ width: "100%" }} />
              </Form.Item>
              <Form.Item name="center_longitude" label="中心经度">
                <InputNumber placeholder="请输入中心经度" style={{ width: "100%" }} />
              </Form.Item>
            </div>
          </div>
        </Form>
      </Modal>

      {/* 批量上传地点弹窗 */}
      <LocationBatchUploadModal
        visible={batchUploadModalVisible}
        onCancel={() => setBatchUploadModalVisible(false)}
        planetId={planetId}
        onSuccess={handleBatchUploadSuccess}
      />
    </div>
  );
};

export default LocationManagement;
